﻿using System.Linq;
using DevExpress.XtraBars;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using NAGFwk.BL;
using NAGFwk.UI;
using SilkeyERP.BL;
using SilkeyERP.Model;
using System;

namespace SilkeyERP.UI.Entities.SalesPerson
{
    public partial class ContentView : BaseContentDetail
    {
        private IBaseController<Model.SalesPerson> _controller = new SalesPersonController();
        public override string ModuleName { get { return "SalesPerson"; } }

        public ContentView()
        {
            InitializeComponent();
        }

        public override void ShowModule(bool firstShow)
        {
            base.ShowModule(firstShow);
            MapItLoad(_controller);
            cityBindingSource.DataSource = new SilkeyERPEntities().City.ToList();
            this.gvBaseContentDetail.OptionsEditForm.CustomEditFormLayout = new CustomEditContentView();
            this.OnUpdateGrid += ContentView_OnUpdateGrid;
            this.OnCancel += ContentView_OnCancel;            
        }

        void ContentView_OnCancel()
        {
            RefreshAll();
        }

        private void ContentView_OnUpdateGrid(object m, RowObjectEventArgs rowObjectEventArgs)
        {
            MapItUpdate(rowObjectEventArgs, _controller);
        }

        private void bbiDelete_ItemClick(object sender, ItemClickEventArgs e)
        {
            MapItDelete(_controller);
        }

        private void bbiRefresh_ItemClick(object sender, ItemClickEventArgs e)
        {
            RefreshAll();
        }

        private void RefreshAll()
        {
            _controller = MapItRefresh(new SalesPersonController());
        }

        private void gvBaseContentDetail_EditFormShowing(object sender, EditFormShowingEventArgs e)
        {
            var view = sender as GridView;
            if (view != null)
            {
                var customEditForm = view.OptionsEditForm.CustomEditFormLayout as CustomEditContentView;
                var myCurrent = (Model.SalesPerson)bsBaseContentDetail.Current;
                if (customEditForm != null)
                    customEditForm.InitData(ref myCurrent);
            }
        }

        protected override void ValidateRows(ValidateRowEventArgs e)
        {
            var current = (Model.SalesPerson)e.Row;
            if (string.IsNullOrEmpty(current.Name)) { e.ErrorText = Properties.Resources.ErrorNameRequired; e.Valid = false; }            
            if (string.IsNullOrEmpty(current.SurName)) { e.ErrorText = Properties.Resources.ErrorSurNameRequired; e.Valid = false; }
            if (string.IsNullOrEmpty(current.SalesPersonCode.ToString())) { e.ErrorText = Properties.Resources.ErrorSalesPersonCodeRequired; e.Valid = false; }
            if (current.BornDate == DateTime.MinValue) { e.ErrorText = Properties.Resources.ErrorBornDateMinValue; e.Valid = false; }
        }

    }
}
